<template>
	<el-card class="leave-review-card">
		<div class="review-header">
			<h3>发表您的评价</h3>
		</div>

		<el-form :model="form" :rules="rules" ref="reviewForm">
			<el-form-item prop="content">
				<el-input v-model="form.content" type="textarea" :rows="4" placeholder="请写下您的真实体验..." maxlength="300"
					show-word-limit></el-input>
			</el-form-item>

			<el-form-item prop="rating" label="评分：">
				<el-rate v-model="form.rating" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" show-text
					:texts="['很差', '一般', '还行', '推荐', '力荐']"></el-rate>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="submitReview" :loading="isSubmitting" round>
					{{ isSubmitting ? '提交中...' : '发表评价' }}
				</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>


<script>
	import {
		postData
	} from '@/axios/http';

	// 明确导入所有用到的Element Plus组件
	import {
		ElButton,
		ElCard,
		ElInput,
		ElForm,
		ElFormItem,
		ElRate,
		ElMessage,
		ElMessageBox
	} from 'element-plus';


	export default {
		components: {
			ElButton, // 必须注册
			ElCard,
			ElInput,
			ElForm,
			ElFormItem,
			ElRate
		},
		props: {
			attractionId: {
				type: Number,
				required: true,
				validator: (value) => {
					// 确保是有效数字且大于0
					return !isNaN(value) && Number(value) > 0
				}
			}
		},
		data() {
			return {
				isSubmitting: false,
				form: {
					content: '',
					rating: 5
				},
				rules: {
					content: [{
							required: true,
							message: '请输入评价内容',
							trigger: 'blur'
						},
						{
							min: 5,
							message: '评价内容至少5个字',
							trigger: 'blur'
						}
					],
					rating: [{
						required: true,
						message: '请选择评分',
						trigger: 'change'
					}]
				}
			}
		},
		beforeMount() {
			// console.log("子组件接收到的attractionId：", this.attractionId)
		},
		methods: {
			async submitReview() {
				// 验证用户登录状态
				const user = uni.getStorageSync('LoginUser');
				if (!user?.userId) {
				  ElMessage.warning('请先登录');
				  return;
				}
				
				
				
				try {
					// 增强表单验证
					if (!this.$refs.reviewForm) {
						throw new Error('表单引用不存在')
					}

					const valid = await this.$refs.reviewForm.validate().catch(err => {
						console.error('表单验证失败:', err)
						throw new Error('表单验证未通过')
					})

					if (!valid) return

					this.isSubmitting = true

					let data = {
						attractionId: this.attractionId,
						userId: user.userId, // 安全访问
						content: this.form.content,
						rating: this.form.rating
					}

					// console.log("要发送的请求：",data)
					//增强请求处理
					const response = await postData('/review', data).catch(err => {
						throw new Error(`请求失败: ${err.message}`)
					})

					if (!response?.data) {
						throw new Error('服务器返回无效数据')
					}
					
					 // 处理业务逻辑
					if (response.data.code === 200) {
						ElMessage.success('评价发表成功');
						
						let date = {
							attractionId: this.attractionId,
							userId: user.userId, // 安全访问
							content: this.form.content,
							rating: this.form.rating
						}
						this.$emit('review-submitted', response.data)
						this.resetForm()
					} else {
						throw new Error(response.data.message || '服务器处理失败')

					}
				} catch (error) {
					 const message = error.response?.data?.message || 
					                 error.message || 
					                 '提交失败，请稍后重试';
					  ElMessage.error(message);
				} finally {
					this.isSubmitting = false;
				}
			},

			resetForm() {
				this.form = {
					content: '',
					rating: 5
				};
				this.$refs.reviewForm.resetFields();
			}
		}
	}
</script>

<style lang="scss">
	.leave-review-card {
		margin-bottom: 20px;
		border-radius: 12px;

		.review-header {
			margin-bottom: 20px;

			h3 {
				font-size: 18px;
				color: var(--el-text-color-primary);
				margin: 0;
			}
		}

		.el-form-item {
			margin-bottom: 20px;

			&:last-child {
				margin-bottom: 0;
				text-align: right;
			}
		}

		.el-rate {
			display: inline-flex;
			align-items: center;

			.el-rate__text {
				margin-left: 10px;
				color: var(--el-text-color-regular);
			}
		}

		.el-button {
			padding: 10px 25px;
		}
	}
</style>